﻿/**
 * Peter
 * Created by: Peter Development Team
 *    http://peter.codeplex.com/
 * 
 * GNU General Public License version 2 (GPLv2)
 *    http://peter.codeplex.com/license
 **/

using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Xml.Serialization;
using Peter.Common.Interfaces;
using Peter.Common.Utilities;

namespace Peter.Data
{
   /// <summary>
   /// Represents the options for the workspace.
   /// </summary>
   [Export (typeof (IOptionData))]
   [PartCreationPolicy (CreationPolicy.Shared)]
   public class WorkspaceOptions : IOptionData, IPartImportsSatisfiedNotification
   {
      internal const string WORK_SPACE_OPTION_NAME = "Peter.Workspace";

      /// <summary>
      /// Initializes a new workspace options object.
      /// </summary>
      public WorkspaceOptions ()
      {
         this.OpenProjects = new Collection <WorkspaceProject> ();
      }

      /// <summary>
      /// Gets the name of the option data.
      /// </summary>
      [XmlIgnore]
      public string Name
      {
         get { return WORK_SPACE_OPTION_NAME; }
      }

      /// <summary>
      /// Gets the peter data.
      /// </summary>
      [XmlIgnore]
      [Import (typeof (IPeterData))]
      public IPeterData PeterData { get; set; }

      /// <summary>
      /// Gets the list of open projects.
      /// </summary>
      public Collection <WorkspaceProject> OpenProjects { get; private set; }

      /// <summary>
      /// Loads the data from xml.
      /// </summary>
      /// <param name="xmlToLoad">Xml string to load.</param>
      public void LoadFromXml (string xmlToLoad)
      {
         WorkspaceOptions loadedData = null;
         try
         {
            loadedData = Serialization.DeserializeFromString<WorkspaceOptions> (xmlToLoad);
         }
         catch (Exception ex)
         {
            Console.Error.Write (ex.Message);
         }

         if (loadedData != null)
            this.CopyPropertiesFrom (loadedData);
      }

      /// <summary>
      /// Saves any data to xml.
      /// </summary>
      /// <returns>The data to save in Xml format.</returns>
      public string SaveToXml ()
      {
         return this.Serialize ();
      }

      /// <summary>
      /// Called when a part's imports have been satisfied and it is safe to use.
      /// </summary>
      public void OnImportsSatisfied ()
      {
         var type = this.GetType ().ToString ();
         this.LoadFromXml (this.PeterData.RequestData (type));
      }
   }
}
